import { provide, ref, Ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "@/utils";
import { TableField, TableUrl } from "@/models/TableSetting";

export default function TableSelect(
  props: {
    url: TableUrl;
    tableFieldList: Array<TableField>;
    submitForm: Record<string, unknown>;
  },
  getRecord: () => void
) {
  // 作废按钮是否可点击
  const invalidDisable: Ref<boolean> = ref(true);
  provide("invalidDisable", invalidDisable);
  // 删除按钮是否可点击
  const deleteDisable: Ref<boolean> = ref(true);
  provide("deleteDisable", deleteDisable);

  // 当前选择的删除项
  const currentPageSelect = ref();
  provide("currentPageSelect", currentPageSelect);
  // 删除项发生变化
  const selectChange = (selects: Array<Record<string, string>>) => {
    currentPageSelect.value = selects;
    invalidDisable.value = selects.length === 0;
    deleteDisable.value = selects.length === 0;
  };

  // 删除事件
  const deleteRecord = () => {
    const selectMultipleId = currentPageSelect.value.map(
      (item: Record<string, unknown>) => item.id
    );
    ElMessageBox.confirm(
      '确认删除 "选中的 ' + selectMultipleId.length + ' 条" 记录吗？',
      "删除",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        api.http
          .postJson(props.url.deleteUrl, selectMultipleId)
          .then(() => {
            getRecord();
            ElMessage.success("删除成功!");
          })
          .catch((err) => {
            console.log(err);
          });
      })
      .catch((cancel) => {
        console.log(cancel);
      });
  };
  provide("deleteRecord", deleteRecord);

  // 作废事件
  const invalidRecord = () => {
    const selectMultipleId = currentPageSelect.value.map(
      (item: Record<string, unknown>) => item.id
    );
    ElMessageBox.confirm(
      '确认作废 "选中的 ' + selectMultipleId.length + ' 条" 记录吗？',
      "作废",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        api.http
          .postJson(props.url.invalidUrl, selectMultipleId)
          .then(() => {
            getRecord();
            ElMessage.success("作废成功!");
          })
          .catch((err) => {
            console.log(err);
          });
      })
      .catch((cancel) => {
        console.log(cancel);
      });
  };
  provide("invalidRecord", invalidRecord);
  return {
    selectChange,
  };
}
